/**
 * @Author: ZFEason
 * @Date: 2023-07-11 14:00:01
 * @LastEditors: ZFEason
 * @LastEditTime: 2023-07-20 17:37:59
 * @FilePath: /ift-economy-network-h5/src/pages/project-scheduling/ApplyScheduling/index.tsx
 * @Description:
 */

import { useEffect, useMemo, useState } from "react";
import {
  Button,
  Checkbox,
  DatePicker,
  Form,
  Input,
  Picker,
  Space,
  TextArea,
  Image,
  Toast,
} from "antd-mobile";
import dayjs from "dayjs";
import { useNavigate, useSearchParams } from "react-router-dom";
import Styles from "./index.module.less";
import rightArrow from "@/assets/image/right_arrow.png";
import presidentOffice from "@/assets/image/president_office.png";
import department from "@/assets/image/department.png";
import { getStorage, setStorage } from "@/utils/storageUtils";
import {
  getInvolvedDeptList,
  getProjectType,
  submitProjectScheduling,
} from "@/service/project-scheduling";

const Index: React.FC<any> = () => {
  const [form] = Form.useForm<any>();
  const navigate = useNavigate();
  const [search] = useSearchParams();
  const role = search.get("role") ?? "1";
  const [detailData, setDetailData] = useState({});

  const [pickerVisible, setPickerVisible] = useState(false);
  const [walkTimeVisible, setWalkTimeVisible] = useState(false);
  const [startTimeVisible, setStartTimeVisible] = useState(false);
  const [warehousingTimeVisible, setWarehousingTimeVisible] = useState(false);
  const [projectType, setProjectType] = useState([]);
  const [involvedDeptList, setInvolvedDeptList] = useState([]);
  const initData = useMemo(
    () => ({
      // 简介信息
      briefIntroduction: [
        {
          name: "本单位承诺在申报信息不存在弄虚作假等情形，所提交的信息均真实、有效。",
        },
        {
          name: "请有意投资落户深圳市福田区的企业（机构），可提交该表，如符合条件我们招商专员会尽快联系您并接洽下一步工作。",
        },
        {
          name: "咨询：深圳市福田区投资推广和企业服务中心 \n0755-88910632",
        },
      ],
      // 行业门类
      industryCategories: [
        { label: "农、林、牧、渔业", value: "福田区工信局" },
        { label: "采矿业", value: "福田区工信局" },
        { label: "制造业", value: "福田区工信局" },
        { label: "电力、热力、燃气及水生产和供应业", value: "福田区发改局" },
        { label: "建筑业", value: "福田区住建局" },
        { label: "批发和零售业", value: "福田区工信局" },
        { label: "交通运输、仓储和邮政业", value: "福田区工信局" },
        { label: "住宿和餐饮业", value: "福田区工信局" },
        { label: "信息传输、软件和信息技术服务业", value: "福田区科创局" },
        { label: "金融业", value: "福田区金融局" },
        { label: "房地产业", value: "福田区住建局" },
        { label: "租赁和商务服务业", value: "福田区工信局" },
        { label: "科学研究和技术服务业", value: "福田区科创局" },
        { label: "水利、环境和公共设施管理业", value: "福田区工信局" },
        { label: "居民服务、修理和其他服务业", value: "福田区工信局" },
        { label: "教育", value: "福田区教育局" },
        { label: "卫生和社会工作", value: "福田区卫健局" },
        { label: "文化、体育和娱乐业", value: "福田区文广旅体局" },
        {
          label: "公共管理、社会保障和社会组织",
          value: "福田区投推和企服中心",
        },
        { label: "国际组织", value: "福田区投推和企服中心" },
      ],
      // 行业地位
      industryStatus: [
        { name: "世界500强", id: "世界500强" },
        { name: "大型央企国企", id: "大型央企国企" },
        { name: "行业龙头", id: "行业龙头" },
        { name: "上市公司", id: "上市公司" },
        { name: "中国500强", id: "中国500强" },
        { name: "独角兽企业", id: "独角兽企业" },
        { name: "专精特新“小巨人”", id: "专精特新“小巨人”" },
        { name: "高新技术企业", id: "高新技术企业" },
        { name: "瞪羚企业", id: "瞪羚企业" },
        { name: "隐形冠军企业", id: "隐形冠军企业" },
        { name: "其他", id: "其他" },
      ],
      // 部门数据
      departmentData: [
        { label: "福田区发改局", value: "福田区发改局" },
        { label: "福田区科创局", value: "福田区科创局" },
        { label: "福田区工信局", value: "福田区工信局" },
        { label: "福田区文广旅体局", value: "福田区文广旅体局" },
        { label: "福田区金融局", value: "福田区金融局" },
        {
          label: "福田区投推和企服中心",
          value: "福田区投推和企服中心",
        },
        { label: "福田区合作区事务署", value: "福田区合作区事务署" },
        {
          label: "福田区香蜜湖建设事务中心",
          value: "福田区香蜜湖建设事务中心",
        },
        {
          label: "福田区活力城区建设事务中心",
          value: "福田区活力城区建设事务中心",
        },
        {
          label: "福田区委组织部（区人才工作局）",
          value: "福田区委组织部（区人才工作局）",
        },
        { label: "福田区委宣传部", value: "福田区委宣传部" },
        { label: "福田区人大办", value: "福田区人大办" },
        { label: "福田区政协办", value: "福田区政协办" },
        { label: "福田区教育局", value: "福田区教育局" },
        { label: "福田区民政局", value: "福田区民政局" },
        { label: "福田区司法局", value: "福田区司法局" },
        {
          label: "福田区财政局（国资局）",
          value: "福田区财政局（国资局）",
        },
        { label: "福田区人力资源局", value: "福田区人力资源局" },
        { label: "福田区住建局", value: "福田区住建局" },
        { label: "福田区水务局", value: "福田区水务局" },
        { label: "福田区卫健局", value: "福田区卫健局" },
        {
          label: "福田区退役军人事务局",
          value: "福田区退役军人事务局",
        },
        { label: "福田区应急管理局", value: "福田区应急管理局" },
        { label: "福田区统计局", value: "福田区统计局" },
        { label: "福田区城管局", value: "福田区城管局" },
        { label: "福田区信访局", value: "福田区信访局" },
        { label: "福田区政数局", value: "福田区政数局" },
        { label: "福田区更新局", value: "福田区更新局" },
        {
          label: "福田区规划土地监察局",
          value: "福田区规划土地监察局",
        },
        {
          label: "福田区机关事务管理局",
          value: "福田区机关事务管理局",
        },
        { label: "福田区工商联", value: "福田区工商联" },
        { label: "福田区发展研究中心", value: "福田区发展研究中心" },
        { label: "福田区物业中心", value: "福田区物业中心" },
        { label: "福田区集体经济署", value: "福田区集体经济署" },
        { label: "福田区建筑工务署", value: "福田区建筑工务署" },
        { label: "福田区国库支付中心", value: "福田区国库支付中心" },
        {
          label: "福田区公共文体发展中心",
          value: "福田区公共文体发展中心",
        },
        { label: "福田园岭街道", value: "福田园岭街道" },
        { label: "福田南园街道", value: "福田南园街道" },
        { label: "福田福田街道", value: "福田福田街道" },
        { label: "福田沙头街道", value: "福田沙头街道" },
        { label: "福田梅林街道", value: "福田梅林街道" },
        { label: "福田华富街道", value: "福田华富街道" },
        { label: "福田香蜜湖街道", value: "福田香蜜湖街道" },
        { label: "福田莲花街道", value: "福田莲花街道" },
        { label: "福田华强北街道", value: "福田华强北街道" },
        { label: "福田福保街道", value: "福田福保街道" },
        { label: "福田市规自局福田局", value: "福田市规自局福田局" },
        { label: "福田区引导基金公司", value: "福田区引导基金公司" },
      ],
      // 是否
      isWhetherData: [
        { label: "是", value: "是" },
        { label: "否", value: "否" },
      ],
      // 经营情况
      operationData: {
        theadData: ["税收贡献（万元）", "营收或产值（万元）"],
        titleColumnData: 1,
      },
      // 经营预测
      businessForecastingData: {
        theadData: [
          "预测企业落户的税收贡献（万元）",
          "预测企业落户的营收或产值（万元）",
        ],
        titleColumnData: 1,
      },
    }),
    []
  );

  // 提交
  const onFinish = async (values: any) => {
    console.log(
      "onFinish---",
      values,
      dayjs(values.walktime).format("YYYY-MM-DD"),
      dayjs(values.starttime).format("YYYY-MM-DD"),
      dayjs(values.warehousingtime).format("YYYY-MM-DD")
    );
    const params = { ...values };
    const res: any = await submitProjectScheduling(params);
    if (res?.code === 0) {
      Toast.show("已提交申请");
      navigate(-1);
    }
  };

  console.log("onFinish---", search.get("role"));
  // 表格自定义校验
  const checkTableRule = (_: any, value: []) => {
    const isTrue = (value ?? []).some((item: []) => item.every(Boolean));

    if (isTrue) {
      return Promise.resolve();
    }
    return Promise.reject(new Error("至少填写一年"));
  };

  const handleStaging = () => {
    console.log("stage---", form.getFieldsValue(true));

    setStorage({
      key: `ApplySchedulingRole${role}`,
      value: form.getFieldsValue(true),
    });
    Toast.show("暂存成功");
    navigate(-1);
  };

  const fetchProjectType = async () => {
    const res: any = await getProjectType();
    const list =
      res?.data?.problemCategory?.map((item: any) => ({
        label: item.name,
        value: item.name,
      })) ?? [];
    res?.code === 0 && setProjectType(list);
  };

  const fetchInvolvedDeptList = async () => {
    const res: any = await getInvolvedDeptList();
    const list =
      res?.data?.problemCategory?.map((item: any) => ({
        label: item.name,
        value: item.name,
      })) ?? [];
    res?.code === 0 && setInvolvedDeptList(list);
  };

  useEffect(() => {
    fetchProjectType();
    fetchInvolvedDeptList();
    const stagingVal = getStorage({
      key: `ApplySchedulingRole${role}`,
    });
    !!stagingVal && form.setFieldsValue(stagingVal);
    !stagingVal && form.resetFields();
    console.log("stagingVal-----", stagingVal);
  }, [role]);

  return (
    <div className={Styles.apply_container}>
      <Image src={role === "2" ? presidentOffice : department} />
      <Form
        form={form}
        layout="vertical"
        // mode="card"
        onFinish={onFinish}
        onValuesChange={(_, allValues) => {
          setDetailData((state) => {
            state = { ...allValues };
            return state;
          });
        }}
        className={`${Styles.form}`}
        footer={
          <div
            className={`bg_ffffff d_between_center ${Styles.footer_container} p_l_r_16`}
          >
            <Button
              className={Styles.submit_btn}
              block
              type="submit"
              color="primary"
              size="large"
            >
              提交
            </Button>

            <Button
              className={Styles.cancel_btn}
              block
              type="button"
              color="primary"
              size="large"
              onClick={handleStaging}
            >
              暂存
            </Button>
          </div>
        }
      >
        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}>项目信息</span>
        </Form.Header>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.glProjectName !== curValues.glProjectName
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <Form.Item
              name="glProjectName"
              label="项目名称"
              rules={[
                {
                  required: true,
                  message: "项目名称不能为空",
                },
              ]}
              trigger="onConfirm"
            >
              <Picker columns={[projectType]}>
                {(_, actions) => (
                  <div className="d_between_center" onClick={actions.open}>
                    {getFieldValue("glProjectName") ? (
                      <span className={`fontsize_14 fw_400 color_333`}>
                        {getFieldValue("glProjectName")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_400 color_666`}>
                        请选择项目名称
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </div>
                )}
              </Picker>
            </Form.Item>
          )}
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}>问题描述</span>
        </Form.Header>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.problemCategory !== curValues.problemCategory
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <Form.Item
              name="problemCategory"
              label="问题类型"
              rules={[
                {
                  required: true,
                  message: "问题类型不能为空",
                },
              ]}
              trigger="onConfirm"
            >
              <Picker columns={[projectType]}>
                {(_, actions) => (
                  <div className="d_between_center" onClick={actions.open}>
                    {getFieldValue("problemCategory") ? (
                      <span className={`fontsize_14 fw_400 color_333`}>
                        {getFieldValue("problemCategory")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_400 color_666`}>
                        请选择问题类型
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </div>
                )}
              </Picker>
            </Form.Item>
          )}
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="projectdebriefing"
          label="项目进展情况及需协调问题"
          rules={[
            {
              required: true,
              message: "项目进展情况及需协调问题不能为空",
            },
          ]}
        >
          <TextArea
            autoSize={{ minRows: 3, maxRows: 5 }}
            placeholder="请输入"
          />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}>需协调内容</span>
        </Form.Header>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.qsjbmId !== curValues.qsjbmId
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <Form.Item
              name="qsjbmId"
              label="涉及部门"
              rules={[
                {
                  required: true,
                  message: "涉及部门不能为空",
                },
              ]}
              trigger="onConfirm"
            >
              <Picker columns={[involvedDeptList]}>
                {(_, actions) => (
                  <div className="d_between_center" onClick={actions.open}>
                    {getFieldValue("qsjbmId") ? (
                      <span className={`fontsize_14 fw_400 color_333`}>
                        {getFieldValue("qsjbmId")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_400 color_666`}>
                        请选择涉及部门
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </div>
                )}
              </Picker>
            </Form.Item>
          )}
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="xtjy"
          label="协调建议"
          rules={[
            {
              required: true,
              message: "协调建议不能为空",
            },
          ]}
        >
          <TextArea
            autoSize={{ minRows: 3, maxRows: 5 }}
            placeholder="请输入"
          />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="zhxt"
          label="分指挥部会议协调情况"
          rules={[
            {
              required: true,
              message: "分指挥部会议协调情况不能为空",
            },
          ]}
        >
          <TextArea
            autoSize={{ minRows: 3, maxRows: 5 }}
            placeholder="请输入"
          />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.uid !== curValues.uid
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <div className={`d_between_center ${Styles.upload_btn_container}`}>
              <div className={`fontsize_14 fw_400 color_666`}>附件</div>
              <div
                className={`${Styles.upload_btn} ${
                  getFieldValue("uid") ? "mb_10" : ""
                }`}
                onClick={() => {}}
              >
                上传文件
              </div>
              {getFieldValue("uid") && (
                <Image src={getFieldValue("uid")} width="100%" />
              )}
            </div>
          )}
        </Form.Item>
      </Form>
    </div>
  );
};
export default Index;
